'use strict';
const Controller = require('egg').Controller;
const {chromium, firefox} = require('playwright');

class SearchController extends Controller {

  async searchTopics(ctx) {
    const tab = ctx.val('tab');
    const kw = ctx.val('q');
    const now_page = parseInt(ctx.val('page')) || 1;
    ctx.logger.info('searchTopics', kw, now_page, ctx.user ? ctx.user.loginname : 'notlogin');

    if (!kw || kw.trim().length == 0) {
      return ctx.redirect('/');
    }

    if (kw.toLocaleLowerCase().includes('vpn')) {
      return ctx.redirect('/');
    }
    if (kw.includes('翻墙')) {
      return ctx.redirect('/');
    }


    if (!tab) {
      // 分派异步任务去处理
      ctx.service.cacheSvc.publish(`${kw}:::::${now_page}`);
    }


    const topics = await this.service.searchSvc.searchTopic(kw, now_page, tab);

    const result = {
      topics,
      kw,
      search_kw: kw,
      page: now_page,
    };

    if (tab) {
      result.tab = tab;
      if (tab == 'podcast') {
        result.pageTitle = kw + ' - 播客搜索';
        if (topics.length == 0) {
          result.search_msg = '没有搜到相关播客';
        }
      }
      result.base_url = `/search?q=${kw}&tab=${tab}&page=`;
      const query = {title: kw, tab: tab};
      let count = await this.service.topicSvc.countTopics(query);
      let page_size = 10;
      result.pages = Math.ceil(count / page_size);
      console.log(result.pages);
      if (result.pages > 10) {
        result.pages = 10;
      }
    } else {
      result.base_url = `/search?q=${kw}&page=`;
      result.pages = 10;
    }

    const ua = this.ctx.headers['user-agent'].toLocaleLowerCase();
    if (ctx.helper.isMobile(ua)) {
      result.ua = 'mobile';
      return await ctx.renderX('search/result_mobile.nj', result);
    } else {
      result.ua = 'pc';
      return await ctx.renderX('search/result_pc.nj', result);
    }
  }


  async pollingBaidu(ctx) {
    const kw = ctx.val('kw');
    const now_page = parseInt(ctx.val('page')) || 1;

    try {
      let topics = await ctx.service.searchSvc.pollingBaidu(kw, now_page);
      return ctx.ok(topics);
    } catch (e) {
      return ctx.ok([]);
    }
  }


  async pollingTsou(ctx) {
    const kw = ctx.val('kw');
    const now_page = parseInt(ctx.val('page')) || 1;

    let topics = await ctx.service.searchSvc.pollingGoogle(kw, now_page);
    return ctx.ok(topics);
  }






  async history() {
    const {ctx} = this;
    await this.ctx.renderX('user/history.nj', {pageTitle: '搜索历史'});
  }
}

module.exports = SearchController;
